package com.wuhan.template.module.home.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wuhan.template.R;
import com.wuhan.template.base.BaseFragment;
import com.wuhan.template.constant.Urls;
import com.wuhan.template.module.find.activity.ChengquActivity;
import com.wuhan.template.module.find.activity.WenzhengActivity;
import com.wuhan.template.module.find.webview.WebViewActivity;
import com.wuhan.template.module.home.activity.ActivityInfoActivity;
import com.wuhan.template.module.home.activity.BaoLiaoActivity;
import com.wuhan.template.module.home.activity.HomeSearchActivity;
import com.wuhan.template.module.home.activity.JiaoYuActivity;
import com.wuhan.template.module.home.activity.ShiMingActivity;
import com.wuhan.template.module.home.activity.ZhiBoactivity;
import com.wuhan.template.module.home.adapter.HomeAdvertisingPageAdapter;
import com.wuhan.template.module.home.adapter.HomeRecyclerAdapter;
import com.wuhan.template.module.home.adapter.HomeRecyclerAdapter2;
import com.wuhan.template.module.home.adapter.HomeRecyclerAdapter3;
import com.wuhan.template.module.home.adapter.HomeRecyclerAdapter4;
import com.wuhan.template.module.home.adapter.HomeRecyclerAdapter5;
import com.wuhan.template.module.home.adapter.HomeRecyclerAdapter6;
import com.wuhan.template.module.home.entity.HomeDetail;
import com.wuhan.template.module.home.listener.MyViewPageListener;
import com.wuhan.template.utils.EventMessage;
import com.wuhan.template.utils.OkHttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Created by mac on 27/4/16.
 */
public class MyFragment extends BaseFragment {

    @BindView(R.id.home_viewPage)
    protected ViewPager viewPager;

    //@BindView(R.id.btn_wenZheng)
    protected Button btnWenZheng;

    @BindView(R.id.home_recyclerView)
    protected RecyclerView recyclerView;

    @BindView(R.id.home_recyclerView2)
    protected RecyclerView recyclerView2;

    @BindView(R.id.home_recyclerView3)
    protected RecyclerView recyclerView3;

    @BindView(R.id.home_recyclerView4)
    protected RecyclerView recyclerView4;

    @BindView(R.id.home_recyclerView5)
    protected RecyclerView recyclerView5;

    @BindView(R.id.home_recyclerView6)
    protected RecyclerView recyclerView6;


    @BindView(R.id.guanggao_title)
    protected TextView guanggaoTitle;

    @BindView(R.id.home_search)
    protected ImageView imageSearch;

    @BindView(R.id.hot)
    protected TextView hot;
    @BindView(R.id.chengshi)
    protected TextView city;
    @BindView(R.id.duban)
    protected TextView duban;
    @BindView(R.id.home_shipin)
    protected TextView shipin;
    @BindView(R.id.zhengwu)
    protected TextView zhengwu;


    private Handler handler = new Handler();

    private int i = 0;
    private HomeDetail[] homeDetails;

    // 务必实现空参数构造方法
    public MyFragment() {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main;
    }

    // 获取参数
    @Override
    protected void getReqParams(Bundle bundle) {
        String tag = bundle.getString("tag");
    }

    @Override
    protected void initViews() {

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                viewPager.setCurrentItem(i++);
                handler.postDelayed(this, 2500);
            }
        }, 2500);
    }

    @Override
    protected void loadData() {
        Map<String, Object> param = new HashMap<>();
        //param.put("pageindex", 3);
        // OkHttpUtils.postSubmitForm(Urls.HOTEL_LIST, param);
        OkHttpUtils.get(Urls.HOME_ADVERTISING, null);
    }


    private List<Map<String, String>> childs_datas = new ArrayList<>();

    @Override
    protected void postEventResult(@NonNull EventMessage message) {
        if (message.type.equals(Urls.HOME_ADVERTISING)) {
            String result = message.result;
            Gson gson = new Gson();
            homeDetails = gson.fromJson(result, HomeDetail[].class);
            //广告栏的显示
            final List<HomeDetail.ContentBean.ChildsDataBean> childs_data = (List<HomeDetail.ContentBean.ChildsDataBean>) homeDetails[0].getContent().get(0).getChilds_data();
            Map<String, String> map1 = null;
            Map<String, String> map2 = null;
            Map<String, String> map3 = null;
            Map<String, String> map4 = null;
            for (int i = 0; i < childs_data.size(); i++) {
                map1 = (Map<String, String>) childs_data.get(0);
                map2 = (Map<String, String>) childs_data.get(1);
                map3 = (Map<String, String>) childs_data.get(2);
         //       map4 = (Map<String, String>) childs_data.get(3);
            }
            childs_datas.add(map1);
            childs_datas.add(map2);
            childs_datas.add(map3);
          //  childs_datas.add(map4);
            HomeAdvertisingPageAdapter adapter = new HomeAdvertisingPageAdapter(getContext(), childs_datas);
            viewPager.setAdapter(adapter);
            adapter.notifyDataSetChanged();

            Map<String,String> text = (Map<String, String>) childs_data.get(0);
            guanggaoTitle.setText(text.get("title"));
            viewPager.addOnPageChangeListener(new MyViewPageListener() {
                @Override
                public void onPageSelected(int position) {
                    i = position;
                    position %= childs_data.size();
                    if (position < 0) {
                        position = childs_data.size() + position;
                    }
                    Map<String,String> texts =(Map<String, String>) childs_data.get(position);
                    guanggaoTitle.setText(texts.get("title"));
                    viewPager.setCurrentItem(i);
                }
            });

            //第二个recyclerView模块的显示
            MyLayoutManager manager = new MyLayoutManager(getContext());
            final List<HomeDetail.ContentBean> contents = homeDetails[1].getContent();
            HomeRecyclerAdapter recyclerAdapter = new HomeRecyclerAdapter(getContext(), contents);
            recyclerView.setLayoutManager(manager);
            recyclerView.setAdapter(recyclerAdapter);

            recyclerAdapter.setOnItemClickListener(new HomeRecyclerAdapter.OnRecyclerViewItemClickListener() {
                @Override
                public void onItemClick(View view, String data) {
                   Intent intent = new Intent(getContext(), WebViewActivity.class);
                    // TODO: 2016/5/16 0016
                    startActivity(intent);
                }
            });


            //第三个recyclerView的显示
            List<HomeDetail.ContentBean> contents2 = homeDetails[2].getContent();
            HomeRecyclerAdapter2 recyclerAdapter2 = new HomeRecyclerAdapter2(getContext(), contents2);
            MyLayoutManager manager2 = new MyLayoutManager(getContext());
            recyclerView2.setLayoutManager(manager2);
            recyclerView2.setAdapter(recyclerAdapter2);

            //第四个recyclerView的显示
            List<HomeDetail.ContentBean> contents3 = homeDetails[3].getContent();
            HomeRecyclerAdapter3 recyclerAdapter3 = new HomeRecyclerAdapter3(getContext(), contents3);
            MyLayoutManager manager3 = new MyLayoutManager(getContext());
            recyclerView3.setLayoutManager(manager3);
            recyclerView3.setAdapter(recyclerAdapter3);

            //第五个recyclerView的显示
            List<HomeDetail.ContentBean> contents4 = homeDetails[4].getContent();
            HomeRecyclerAdapter4 recyclerAdapter4 = new HomeRecyclerAdapter4(getContext(), contents4);
            MyLayoutManager manager4 = new MyLayoutManager(getContext());
            recyclerView4.setLayoutManager(manager4);
            recyclerView4.setAdapter(recyclerAdapter4);

            //第六个recyclerView的显示
            List<HomeDetail.ContentBean> contents5 = homeDetails[5].getContent();
            HomeRecyclerAdapter5 recyclerAdapter5 = new HomeRecyclerAdapter5(getContext(), contents5);
            MyLayoutManager manager5 = new MyLayoutManager(getContext());
            recyclerView5.setLayoutManager(manager5);
            recyclerView5.setAdapter(recyclerAdapter5);

            //第七个recyclerView的显示
            List<HomeDetail.ContentBean> contents6 = homeDetails[6].getContent();
            HomeRecyclerAdapter6 recyclerAdapter6 = new HomeRecyclerAdapter6(getContext(), contents6);
            MyLayoutManager manager6 = new MyLayoutManager(getContext());
            recyclerView6.setLayoutManager(manager6);
            recyclerView6.setAdapter(recyclerAdapter6);


            hot.setText(homeDetails[2].getTitle());
            city.setText(homeDetails[3].getTitle());
            duban.setText(homeDetails[4].getTitle());
            shipin.setText(homeDetails[5].getTitle());
            zhengwu.setText(homeDetails[6].getTitle());
        }



        //首页的搜索选项
        imageSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), HomeSearchActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
    }


    @Override
    public void onDestroy() {

        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    //跳转大问政的button
    @OnClick(R.id.btn_wenZheng)
    public void goWenZheng(View view) {
        Intent intent = new Intent(getContext(), WenzhengActivity.class);
        startActivity(intent);

    }

    //跳转到报料的button
    @OnClick(R.id.btn_baoliao)
    public void goBaoLiao(View view) {
        Intent intent = new Intent(getContext(), BaoLiaoActivity.class);
        getContext().startActivity(intent);

    }

    //跳转到城区的button
    @OnClick(R.id.btn_home_chengqu)
    public void goChengqu(View view) {
        Intent intent = new Intent(getContext(), ChengquActivity.class);
        getContext().startActivity(intent);

    }
    //跳转到直播的button
    @OnClick(R.id.btn_home_zhibo)
    public void goZhibo(View view) {
        Intent intent = new Intent(getContext(), ZhiBoactivity.class);
        getContext().startActivity(intent);

    }


    //跳转到市民之家的button
    @OnClick(R.id.shimingzhijei)
    public void goShiMing(View view) {
        Intent intent = new Intent(getContext(), ShiMingActivity.class);
        getContext().startActivity(intent);
    }

    //跳转到活动的button
    @OnClick(R.id.activity_info)
    public void goActivity(View view) {
        Intent intent = new Intent(getContext(), ActivityInfoActivity.class);
        getContext().startActivity(intent);
    }

    //跳转到教育的button
    @OnClick(R.id.btn_jiaoyu)
    public void goJiaoYu(View view) {
        Intent intent = new Intent(getContext(), JiaoYuActivity.class);
        getContext().startActivity(intent);
    }

    //跳转到更多的button
    @OnClick(R.id.btn_home_more)
    public void goMore(View view) {
        FragmentManager supportFragmentManager = ((AppCompatActivity) (getContext())).getSupportFragmentManager();
        Map<String, String> params = new HashMap<>();
        params.put("tag2", "2");
        ZiXunFragment ziXunFragment = BaseFragment.newInstance(ZiXunFragment.class, params);
        supportFragmentManager.beginTransaction().replace(R.id.fl_main, ziXunFragment).commit();
    }


    /**
     * 重写LinearLayoutManager实现recyclerView自适应item的高度
     */
    public class MyLayoutManager extends LinearLayoutManager {

        private static final int CHILD_WIDTH = 0;
        private static final int CHILD_HEIGHT = 1;
        private static final int DEFAULT_CHILD_SIZE = 100;

        private final int[] childDimensions = new int[2];

        private int childSize = DEFAULT_CHILD_SIZE;
        private boolean hasChildSize;


        private int[] mMeasuredDimension = new int[2];

        public MyLayoutManager(Context context) {
            super(context);
        }


        @Override
        public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
            final int widthMode = View.MeasureSpec.getMode(widthSpec);
            final int heightMode = View.MeasureSpec.getMode(heightSpec);
            final int widthSize = View.MeasureSpec.getSize(widthSpec);
            final int heightSize = View.MeasureSpec.getSize(heightSpec);
            int width = 0;
            int height = 0;


            for (int i = 0; i < getItemCount(); i++) {

                try {
                    measureScrapChild(recycler, i,
                            widthSpec,
                            View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                            mMeasuredDimension);
                } catch (IndexOutOfBoundsException e) {

                    e.printStackTrace();
                }

                if (getOrientation() == HORIZONTAL) {
                    width = width + mMeasuredDimension[0];
                    if (i == 0) {
                        height = mMeasuredDimension[1];
                    }
                } else {
                    height = height + mMeasuredDimension[1];
                    if (i == 0) {
                        width = mMeasuredDimension[0];
                    }
                }
            }


            switch (widthMode) {
                case View.MeasureSpec.EXACTLY:
                case View.MeasureSpec.AT_MOST:
                case View.MeasureSpec.UNSPECIFIED:
            }

            switch (heightMode) {
                case View.MeasureSpec.EXACTLY:
                    height = heightSize;
                case View.MeasureSpec.AT_MOST:
                case View.MeasureSpec.UNSPECIFIED:
            }
            setMeasuredDimension(widthSpec, height);

        }

        private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec, int heightSpec, int[] measuredDimension) {
            View view = recycler.getViewForPosition(position);


            if (view != null) {
                RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
                int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                        getPaddingTop() + getPaddingBottom(), p.height);
                view.measure(widthSpec, childHeightSpec);
                measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
                measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
                recycler.recycleView(view);
            }
        }

        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            super.onLayoutChildren(recycler, state);
        }

    }
}
